package br.com.wayloc.track.adapters;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import br.com.wayloc.track.R;
import br.com.wayloc.track.models.NavDrawerItem;

public class CustomListAdapter extends BaseAdapter {
	
	private Context context;
	private ArrayList<NavDrawerItem> navDrawerItems;

	public CustomListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
		this.context = context;
		this.navDrawerItems = navDrawerItems;
	}

	@Override
	public int getCount() {
		return navDrawerItems.size();
	}

	@Override
	public Object getItem(int position) {		
		return navDrawerItems.get(position);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	public ArrayList<NavDrawerItem> getItems(){
		return navDrawerItems;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		JSONObject json = new JSONObject();

		//if (convertView == null) {
			LayoutInflater mInflater = (LayoutInflater)
				context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

			convertView = mInflater.inflate(R.layout.sidebar_listview_item, null);
		//}

		ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
		TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
		TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
		
		if (navDrawerItems.get(position).getIcon()!=0)
			imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
		//else
			//imgIcon.setVisibility(View.GONE);

		if (navDrawerItems.get(position).getCount()!="")
			txtCount.setText(navDrawerItems.get(position).getCount());
		else
			txtCount.setVisibility(View.GONE);
		//System.out.println(navDrawerItems.get(position));

		try{
			//System.out.println(navDrawerItems.get(position).getComando());
			json = (JSONObject) new JSONTokener(navDrawerItems.get(position).getComando()).nextValue();
			txtTitle.setTag(json);
		}catch (JSONException e) {
		}
		txtTitle.setText(navDrawerItems.get(position).getTitle());
		
		if (navDrawerItems.get(position).getSub()){
			//RelativeLayout layout = (RelativeLayout) convertView.findViewById(R.id.relativeitem);
			//layout.setBackgroundColor(Color.parseColor("#75a00e"));
			MarginLayoutParams params = (MarginLayoutParams) imgIcon.getLayoutParams();
			params.leftMargin = 48;
			imgIcon.setLayoutParams(params);
		}

		return convertView;
	}

}